<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view" style="overflow-y:scroll;overflow-x:hidden;height:100%">
      <el-row :gutter="20" style="margin: 0px -50px 20px 5px;">
        <el-col :span="21" v-if="route.query.state1=='0'"><h1 class="my-heading">创建考试</h1></el-col>
        <el-col :span="21"  v-else-if="route.query.state1=='1'"><h1 class="my-heading">编辑考试</h1></el-col>
      </el-row>
      <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="120px" >
        <el-row :gutter="24">
          <el-col :span="7" class="mb20">
            <el-form-item label="考试名称" prop="examName">
              <el-input v-model="form.examName" placeholder="请输入考试名称"  :disabled="started"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="7" class="mb20">
            <el-form-item  label="参考组织" prop="groupIds">
              <el-cascader disabled v-model="form.groupIds" ref="cascaderAddr1" style="width: 420px" placeholder="请选择标签"  @change="handleCascaderChange1"
              :props="{ value: 'id', label: 'name', children: 'children',checkStrictly: true }" :options="options1" clearable filterable>
              </el-cascader>
            </el-form-item>
            <el-form-item label="参考岗位" prop="postNames">
              <el-select disabled   @change="getItem1" v-model="form.postNames" multiple collapse-tags collapse-tags-tooltip placeholder="请选择" style="width: 240px">
                <el-option v-for="item in postList" :key="item.postIds" :label="item.postName" :value="item.postName"/>
              </el-select>
            </el-form-item>
            <el-form-item label="参考人员" prop="personName" v-if="route.query.state1=='1'">
              <el-select  disabled @change="getItem2" v-model="persons1"  multiple filterable collapse-tags collapse-tags-tooltip  placeholder="请选择" style="width: 240px">
                <el-checkbox v-model="checked" @change='selectAll' style="margin-left: 20px">全选</el-checkbox>
                <el-option v-for="item in personList" :key="item.username" :label="item.name+'-'+item.postName" :value="item.username"/>
              </el-select>
            </el-form-item>
            <el-form-item label="参考人员" prop="personName" v-if="route.query.state1=='0'">
                <el-select disabled v-model="form.personName" placeholder="请选择" style="width: 240px">
                    <el-option v-for="item in options" :key="item.personName" :label="item.personName" :value="item.personName"/>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" class="mb20">
            <el-form-item label="选择试卷" prop="examPaperName">
              <el-input v-model="form.examPaperName" placeholder="请输入" disabled/>
              <el-button type="primary" v-if="flag == 0 && route.query.state1=='0'" :disabled="form.examName.length==0" text @click="formDialogRef.openDialog(form.groupIds,form.postIds,form.examPaperId,0)">新建试卷</el-button>
              <el-button type="primary" v-if="form.examPaperId && isShow" :disabled="form.examName.length==0 || started" text @click="formDialogRef.openDialog(form.groupIds,form.postIds,form.examPaperId,1,form.examId)">编辑试卷</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="16" class="mb20">
            <el-form-item label="考试说明" prop="examRemark">
              <el-input  type="textarea" v-model="form.examRemark" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="5" class="mb20">
            <el-form-item label="考试时长" prop="examTime">
              <el-input-number v-model="form.examTime" :min="30" :max="120" />
            </el-form-item>
          </el-col>
          <el-col :span="2" style="margin-left: -12px">
            <el-text class="input3">分钟</el-text>
          </el-col>
        </el-row>
        <el-row :gutter="24">
<!--          <el-col :span="6" class="mb20">-->
<!--            <el-form-item label="定时交卷" prop="submitOntimeState">-->
<!--              <el-switch v-model="form.submitOntimeState" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="6" class="mb20">
            <el-form-item label="提前交卷" prop="submitInadvanceState">
              <el-switch v-model="form.submitInadvanceState"  :active-value="0" :inactive-value="1"/>
            </el-form-item>`
          </el-col>
<!--          <el-col :span="24" class="mb20">-->
<!--            <el-text style="margin-left: 100px;font-size: 14px;color: #817B7B;">注:对于排名可设置"厂、车间、工段"区分，可多选如成绩相同时,按照答题时长进行排名</el-text>-->
<!--          </el-col>-->
        </el-row>
        <el-row :gutter="24">
          <el-col :span="2" class="mb20">
            <el-form-item label="允许交卷时间：" style="margin-left: 12px"></el-form-item>
          </el-col>
          <el-col :span="6" class="mb20">
            <el-form-item label="考试开始后" prop="allowStartTime">
              <el-input-number v-model="form.allowStartTime" :min="1" :max="60" />
            </el-form-item>
          </el-col>
          <el-col :span="2" style="margin-left: -12px">
            <el-text class="input3">分钟</el-text>
          </el-col>
<!--          <el-col :span="6" style="margin-left: -42px">-->
<!--            <el-form-item label="考试截止前" prop="allowEndTime">-->
<!--              <el-input-number v-model="form.allowEndTime" :min="1" :max="60" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="2" style="margin-left: -12px">-->
<!--            <el-text class="input3">分钟</el-text>-->
<!--          </el-col>-->
        </el-row>
        <el-row :gutter="24">
          <el-col :span="5" class="mb20">
            <el-form-item label="错题优先" prop="wrongQuestionFirstState">
              <el-switch v-model="form.wrongQuestionFirstState"  :active-value="1" :inactive-value="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6" class="mb20">
            <el-form-item label="考试结束前" prop="sendRemindTime">
              <el-input-number v-model="form.sendRemindTime" :min="1" :max="60"/>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="margin-left: -12px">
            <el-text class="input3">分钟发送提醒(加默认值)</el-text>
          </el-col>
        </el-row>
        <div class="line"></div>
        <el-row :gutter="24">
            <el-col :span="11" class="mb20" style="margin-left: 50px">
              <el-text style="line-height: 50px;margin-left: 10px;font-size: 16px">完成试卷</el-text>
              <el-form-item style="margin-left: 60px;font-weight: bold" label="及格分数:">
                <div style="display: flex">
                  <el-text >{{passMark}}分</el-text>
                </div>
              </el-form-item>
              <el-form-item  style="margin-left: -100px" label="" v-for="item in scoreList" :key="item.id">
                <el-input-number v-model="item.leftBoundary"  @change="changeMark":min="0" :max="100" class="input5"/>
                <el-text style="font-weight: bold;margin-left: 5px;margin-right: 5px"><=得分<</el-text>
                <el-input-number v-model="item.rightBoundary" :min="1" :max="100" class="input5"/>
                <el-text class="content1">评价:</el-text>
                <el-input v-model="item.scoreLevel" placeholder="" class="input4"/>
              </el-form-item>
            </el-col>

          <el-col :span="11" class="mb20" style="margin-left: 0px">
            <el-text class="content">试题显示</el-text>
            <el-form-item style="margin-left: 50px" label="试题顺序：" prop="questionOrder">
              <el-radio-group v-model="form.questionOrder">
                <el-radio :label="0">顺序</el-radio>
                <el-radio :label="1">随机</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="选项顺序：" prop="optionsOrder">
              <el-radio-group v-model="form.optionsOrder">
                <el-radio :label="0">顺序</el-radio>
                <el-radio :label="1">随机</el-radio>
              </el-radio-group>
            </el-form-item>
            <div><el-text style="margin-left: 100px;font-size: 14px;color: #817B7B;">打乱顺序可以防止考生之间传递答案</el-text></div>
            <el-form-item style="margin-top: 30px"  label="结束页面" prop="finishExamState">
              <el-radio-group v-model="form.finishExamState">
                <el-radio :label="0">不显示成绩</el-radio>
<!--                <el-radio :label="1">显示成绩</el-radio>-->
<!--                <el-radio :label="2">显示成绩、答案详情</el-radio>-->
                <el-radio :label="1">显示成绩、答案详情、答案解析</el-radio>
              </el-radio-group>
            </el-form-item>
<!--            <el-text class="content">成绩查询</el-text>-->
<!--            <el-form-item  label="查询" prop="selectGradesState">-->
<!--              <el-radio-group v-model="form.selectGradesState">-->
<!--                <el-radio :label="0" >不允许查询</el-radio>-->
<!--                <el-radio :label="1">允许查询成绩、排名</el-radio>-->
<!--                <el-radio :label="2" >允许查询成绩、排名、答题详情，可以练习错题</el-radio>-->
<!--              </el-radio-group>-->
<!--            </el-form-item>-->
<!--            <el-text style="margin-left: 100px;font-size: 14px;color: #817B7B;">注:对于排名可设置"厂、车间、工段"区分，可多选,如成绩相同时,按照答题时长进行排名</el-text>-->
          </el-col>
        </el-row>
        <el-row :gutter="24">
            <el-col :span="24" class="mb20">
              <div style="text-align:center">
                <el-button type="primary" @click="onSubmit" :disabled="loading" >保存考试</el-button>
                <el-button type="danger" @click="goBack">取消</el-button>
              </div>
            </el-col>
        </el-row>
      </el-form>
    </div>
    <el-dialog v-model="innerVisible" width="400" style="font-weight: bold" title="提醒" append-to-body center>
      <span style="font-size: 16px;margin-left: 30px">考试区间需大于考试时长,请重新设定</span>
    </el-dialog>
    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" @parentsEmit="pEmitData"/>
  </div>
</template>

<script setup lang="ts" name="KsglExamListIndex1">
  import { useDict } from '/@/hooks/dict';
  import { useMessage } from "/@/hooks/message";
  import { getObj, putObj,getUsers} from '/@/api/train/ksglExamList'
  import { rule } from '/@/utils/validate';
  import { useRoute } from 'vue-router';
  import { defineEmits, reactive, ref ,onMounted } from 'vue';
  import {deptTree, syspost} from "/@/api/train/kszlData";
  import { Action, ElMessage, ElMessageBox } from 'element-plus';
  import { useRouter } from 'vue-router';
  import {
    examdetailsList,
    score,
    sededitList,
    examinationList,
    identification,
    putObjsty,
  } from '/@/api/train/xxrwTaskList';
  const emit = defineEmits(['refresh']);
  // 引入组件
  const FormDialog = defineAsyncComponent(() => import('./form.vue'));
  const cascaderAddr = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
  const cascaderAddr1 = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
  // 定义变量内容
  const started = ref(false);
  const passMark = ref();
  const flag = ref(0)
  const isShow = ref(true)
  const persons1 = ref()
  const namelist = ref()
  const dataFormRef = ref();
  const visible = ref(false)
  const loading = ref(false)
  const innerVisible = ref(false)
  // 缓存当前选中节点的key
  const cacheNodeKey = ref("");
  // 缓存拼接后的文本
  const cacheJoinLabel = ref("");
  const dataList = ref<any[]>([]); // 根据你的数据结构来定义类型
  // 定义变量内容
  const formDialogRef = ref()
  const xxrwTaskRelateDateList = ref([]);
  // 定义字典
  //参与组织数据
  const options1 = ref<any[]>([]);
  const personList = reactive([{}])
  //部门主键
  const pkDept = ref()
  const durationInMinutes = ref()
  //学习岗位
  const postList =reactive([{}])
  const formquerlist = reactive({
    isRelateExam:'',
    taskId:'',
    examId: '',
    examName: ''
  })
  // 提交表单数据
  const formquer = reactive({
    taskName:'',
    zymcName:'',
    keyPoint:'',
    startTime:'',
    endTime:'',
    abnormalDays:'',
    state:'',
    isTimeLimit: '',
    isRelateExam:'',
    isTopicEnd:'',
    isExcutePlan:'',
    isExamAfterData:'',
    zymcId:'',
    keyId:'',
    postId:''
  })
  const form = reactive({
    id:'',
    groupIds:[],
    examName: '',
    postIds:[],
    // examLabel: '',
    // adminName: '',
    examPaperName: '',
    examPaperId:'',
    groupNames: '',
    persons1:[{}],
    personName:'',
    examTime:'30',
    xxrwTranscriptEntityList:[],
    levelEntityList1:[],
    examRemark: '',
    // submitOntimeState: true,
    submitInadvanceState: 1,
    allowStartTime: '15',
    allowEndTime: '10',
    wrongQuestionFirstState: 1,
    sendRemindTime: '20',
    questionOrder: 1,
    optionsOrder: 1,
    finishExamState: 1,
    selectGradesState: 2,
    remark: '',
    posts:[],
  });
  const checked = ref(false)
  const router = useRouter();
  const groupNames = ref([])
  const groupIds = ref([])
  const processedPKPosts = ref([])
  const scoreList = reactive([])
  // 定义校验规则
  const dataRules = ref({
    examName: [{required: true, message: '考试名称不能为空', trigger: 'blur'}],
    examLabel: [{required: true, message: '考试标签不能为空', trigger: 'blur'}],
    adminGroupId: [{required: true, message: '管理员组织不能为空', trigger: 'blur'}],
    adminName: [{required: true, message: '管理员姓名不能为空', trigger: 'blur'}],
    adminUserName: [{required: true, message: '管理员工号不能为空', trigger: 'blur'}],
    examPaperName: [{required: true, message: '试卷名称不能为空', trigger: 'blur'}],
    groupId: [{required: true, message: '考试组织名称不能为空', trigger: 'blur'}],
    postId: [{required: true, message: '参考岗位名称不能为空', trigger: 'blur'}],
    examType: [{required: true, message: '考试类型不能为空', trigger: 'blur'}],
    persons1: [{required: true, message: '参与人员不能为空', trigger: 'blur'}],
    submitOntimeState: [{required: true, message: '定时交卷不能为空', trigger: 'blur'}],
    submitInadvanceState: [{required: true, message: '提前交卷不能为空', trigger: 'blur'}],
    electronicInvigilationState: [{required: true, message: '电子监考不能为空', trigger: 'blur'}],
    allowMakeupExamState: [{required: true, message: '是否允许补考不能为空', trigger: 'blur'}],
    allowStartTime: [{required: true, message: '考试开始后的时间不能为空', trigger: 'blur'}],
    cutscreenTimes: [{required: true, message: '允许切屏次数不能为空', trigger: 'blur'}],
    examTime: [{required: true, message: '考试时长不能为空', trigger: 'blur'}],
    sendRemindTime: [{required: true, message: '考试结束前不能为空', trigger: 'blur'}],
    questionOrder: [{required: true, message: '试题顺序不能为空', trigger: 'blur'}],
    optionsOrder: [{required: true, message: '选项顺序不能为空', trigger: 'blur'}],
    examTimeState: [{required: true, message: '考试状态不能为空', trigger: 'blur'}],
    finishExamState: [{required: true, message: '结束页面不能为空', trigger: 'blur'}],
    selectGradesState: [{required: true, message: '查询不能为空', trigger: 'blur'}],
    allowEndTime: [{required: true, message: '考试结束前的时间不能为空', trigger: 'blur'}],
  })
  // const id = ref()
  //挂载完毕
  const route = useRoute();
  onMounted(()=> {
    processQueryParams();
    deptTreeList()
    // 新增
  })
  const processQueryParams = () =>{
    formquer.state = route.query.state
    // scoreList.length = 0
    // 上一个页面判断编辑
    console.log(route.query.state,'是否会');
    if (route.query.state == '1') {
    //   本页面 编辑学习任务==>新增考试
      console.log(route.query.state1,'hhhh');
      if (route.query.state1 == "0") {
        let arr = [
          { id: 1, leftBoundary: 0, rightBoundary: 60, scoreLevel: "不及格", },
          { id: 2, leftBoundary: 60, rightBoundary: 80, scoreLevel: "及格", },
          { id: 3, leftBoundary: 80, rightBoundary: 100, scoreLevel: "优秀", },
          { id: 4, leftBoundary: 100, rightBoundary: 100, scoreLevel: "完美", }
        ]
        Object.assign(scoreList, arr)
        console.log(scoreList, arr, '7217');
        passMark.value = scoreList[1].leftBoundary
        const taskId = route.query.taskId
        formquer.isRelateExam = route.query.isRelateExam
        console.log(formquer.isRelateExam,'关联考试');
        console.log(taskId, route.query.taskId, '接收学习任务id');
        form.groupIds = route.query.orgId
        // console.log( form.groupIds,'组织')
        form.groupNames = route.query.orgName
        form.postNames = route.query.postName
        form.postIds = route.query.postId
        // console.log(form.postIds,'岗位id');
        form.personName = route.query.persons
        console.log(form.personName,'名称');
        // form.persons1 = route.query.personInfo
        const personsJson = route.query.personInfo
        form.persons1 = personsJson ? JSON.parse(personsJson) : [];
        // console.log(form.persons1,route.query.personInfo,'info');
        formquer.taskName = route.query.taskName
        formquer.zymcName = route.query.zymcName
        formquer.zymcId = route.query.zymcId
        formquer.keyId = route.query.keyId,
        formquer.postId = route.query.postId
        // console.log(formquer.zymcName,'接收专业名称');
        formquer.keyPoint = route.query.keyPoint
        formquer.startTime = route.query.startTime
        formquer.endTime = route.query.endTime
        formquer.abnormalDays = route.query.abnormalDays
        formquer.state = route.query.state
        // console.log('接收岗位id',route.query.postId12);
        // console.log(formquer.state,route.query.state);
        formquer.isTimeLimit = route.query.isTimeLimit
        formquer.isTopicEnd = route.query.isTopicEnd
        formquer.isExcutePlan = route.query.isExcutePlan
        formquer.isExamAfterData = route.query.isExamAfterData

        // 获取查询参数中的 data 字符串  资料数据
        const dataString = route.query.encodedData;
        // 将字符串转换回数组
        const dataToPass = JSON.parse(dataString);
        // 现在你可以使用 dataToPass 数组了
        // console.log(dataToPass, '接收到的资料选择')
      }
      else{
      //  正常编辑
        console.log(route.query.state1, 'route.query.state1');
        const examId = route.query.examId;
        const taskId = route.query.taskId
        console.log('examId', examId, route.query.examId);
        console.log(taskId, route.query.taskId, '接收学习任务id');
        examdetailsList(examId).then((res) => {
          Object.assign(form, res.data)
          form.groupIds = form.groupId.split(",")
          form.groupNames = form.groupName.split("/")
          form.postNames = form.postName.split(",")
          form.postIds = form.postId.split(",")
          form.examPaperId = form.examPaperId
          console.log(form.examPaperId,'组卷id');
          form.xxrwTranscriptEntityList.forEach(item => {
            let username = item.userName
            persons1.value.push(username)
          })
          console.log(form.transcriptEntityList, 'item.userName');
          form.questionOrder = form.questionOrder
          getPostList()
          getPerson()
          score(examId).then((res => {
            Object.assign(scoreList, res.data)
            passMark.value = scoreList[1].leftBoundary
            console.log('score',scoreList,passMark.value);
          }))
        })
      }
    }else{
      // 正常新增---编辑考试修改
      console.log(route.query.state1, 'route.query.state1');
      const examId1 = route.query.examId1;
      const taskId = route.query.taskId
      console.log('examId', examId1, route.query.examId1);
      console.log(taskId, route.query.taskId, '接收学习任务id');
      if( examId1==undefined ){
        let arr = [
          { id: 1, leftBoundary: 0, rightBoundary: 60, scoreLevel: "不及格", },
          { id: 2, leftBoundary: 60, rightBoundary: 80, scoreLevel: "及格", },
          { id: 3, leftBoundary: 80, rightBoundary: 100, scoreLevel: "优秀", },
          { id: 4, leftBoundary: 100, rightBoundary: 100, scoreLevel: "完美", }
        ]
        Object.assign(scoreList, arr)
        passMark.value = scoreList[1].leftBoundary
        form.groupIds = route.query.content
        // console.log( form.groupIds,'组织')
        form.groupNames = route.query.content2
        form.postIds = route.query.content1
        form.postNames = route.query.content3
        const personsJson = route.query.persons
        form.persons1 = personsJson ? JSON.parse(personsJson) : [];
        form.personName = route.query.namesss
        console.log(form.personName,'名称');
        formquer.taskName = route.query.taskName
        formquer.zymcName = route.query.zymcName
        formquer.keyPoint = route.query.keyPoint
        formquer.startTime = route.query.startTime
        formquer.endTime = route.query.endTime
        formquer.abnormalDays = route.query.abnormalDays
        formquer.state = route.query.state
        // console.log('接收岗位id',route.query.postId12);
        // console.log(formquer.state,route.query.state);
        formquer.isTimeLimit = route.query.isTimeLimit
        formquer.isRelateExam = route.query.isRelateExam
        formquer.isTopicEnd = route.query.isTopicEnd
        formquer.isExcutePlan = route.query.isExcutePlan
        formquer.isExamAfterData = route.query.isExamAfterData
        // 获取查询参数中的 data 字符串  资料数据
        const dataString = route.query.encodedData;
        // 将字符串转换回数组
        const dataToPass = JSON.parse(dataString);
        // 现在你可以使用 dataToPass 数组了
        console.log(dataToPass, '接收到的资料选择')
      }else{
        examdetailsList(examId1).then((res) => {
          Object.assign(form, res.data)
          form.groupIds = form.groupId.split(",")
          form.groupNames = form.groupName.split("/")
          form.postNames = form.postName.split(",")
          form.postIds = form.postId.split(",")
          form.examPaperId = form.examPaperId
          console.log(form.examPaperId,'组卷id');
          form.xxrwTranscriptEntityList.forEach(item => {
            let username = item.userName
            persons1.value.push(username)
          })
          console.log(form.transcriptEntityList, 'item.userName');
          form.questionOrder = form.questionOrder
          getPostList()
          getPerson()
          score(examId1).then((res => {
            Object.assign(scoreList, res.data)
            passMark.value = scoreList[1].leftBoundary
            console.log('score',scoreList,passMark.value);
          }))
        })
      }
      }

  }
  const selectAll=() =>{
    if (checked.value) {
      persons1.value = personList.map(person => person.username);
      form.persons1.length = 0
      personList.forEach(item =>{
        for (let i = 0; i < persons1.value.length; i++) {
          if (item.username == persons1.value[i]) {
            form.persons1.push({
              personName:item.name,
              postId:item.pkPost,
              userName:item.username,
              postName:item.postName,
              pkPsndoc:item.pkPsndoc,
              groupId:form.groupIds,
              groupName:form.groupNames,
            })
          }
        }
      })
    }else {
      persons1.value.length = 0
      form.persons1.length = 0
    }
  }
  const pEmitData=(data:any)=>{
    if(data.id!==undefined){
      form.examPaperId = data.id
      form.examPaperName = data.name
      flag.value = 1
      isShow.value = true
    }else {
      form.examPaperName = data.name
    }
    console.log('data----',data,form.examPaperId)
  }
  const handleChange = () =>{
    console.log('scoreList', scoreList);
    // 使用扩展运算符创建浅拷贝
  }
  const getPerson = ()=>{
    processedPKPosts.value.length=0
    form.postIds.forEach(item=>{
      if (item.includes(',')) {
        // 如果项包含逗号，则按逗号拆分
        const splitItems = item.split(',');
        splitItems.forEach(splitItem=>{
          processedPKPosts.value.push(splitItem.trim())
        })
      }else {
        processedPKPosts.value.push(item)
      }
    })
    // 使用map将数组中的每个元素转换为URL参数形式，并用join连接它们
    const params = processedPKPosts.value.map((id, index) => {
      // 注意：这里index > 0时添加'&'，因为第一个元素前不需要
      return index > 0 ? '&pkPosts=' + id : 'pkPosts=' + id;
    }).join('');
    // console.log('params',params)
    getUsers(params).then((res=>{
      Object.assign(personList,res)
      checked.value = true
      selectAll()
    }))
  }
  const getItem2=(val:any) =>{
    form.persons1.length = 0
    if(persons1.value.length<personList.length){
      checked.value = false
    }
    personList.forEach(item =>{
      for (let i = 0; i < val.length; i++) {
        if (item.username == val[i]) {
          form.persons1.push({
            personName:item.name,
            postId:item.pkPost,
            userName:item.username,
            postName:item.postName,
            pkPsndoc:item.pkPsndoc,
            groupId:form.groupIds,
            groupName:form.groupNames,
          })
        }
      }
    })
  }
  // 节点节点事件
  const handleNodeClickEvent = (node: Node) => {
    console.log('节点----',node)
  };
  const changeMark =()=>{
    passMark.value =scoreList[1].leftBoundary
  }
  const getItem1=(val:any) =>{
    let pkPosts = [];
    form.posts.length = 0
    personList.length = 0
    form.persons1.length = 0
    postList.forEach(item => {
      for (let i = 0; i < val.length; i++) {
        if (item.postName == val[i]) {
          pkPosts.push(item.postsString)
          form.posts.push(item)
          // console.log(form.studyPost,'form');
        }
      }
    })
    console.log(pkPosts,'查看数组内容'); // 查看数组内容
    processedPKPosts.value.length=0
    pkPosts.forEach(item=>{
      if (item.includes(',')) {
        // 如果项包含逗号，则按逗号拆分
        const splitItems = item.split(',');
        splitItems.forEach(splitItem=>{
          processedPKPosts.value.push(splitItem.trim())
        })
      }else {
        processedPKPosts.value.push(item)
      }
    })
    console.log('processedPKPosts',form.posts)
    // 使用map将数组中的每个元素转换为URL参数形式，并用join连接它们
    const params = processedPKPosts.value.map((id, index) => {
      // 注意：这里index > 0时添加'&'，因为第一个元素前不需要
      return index > 0 ? '&pkPosts=' + id : 'pkPosts=' + id;
    }).join('');
    console.log('params',params)
    getUsers(params).then((res=>{
      Object.assign(personList,res)
      console.log('111、、、',personList)
    }))
    // if (route.query.flag == 1){
    //   isShow.value = false
    //   flag.value = 0
    //   form.examPaperName = ''
    // }
  }
  // 参与组织
  const deptTreeList = async () => {
    deptTree().then((res) => {
      options1.value = res.data;
      // console.log('111、、、',options1.value)
    });
  };
  //拿到树节点id
  const treeHandleChange = (value:any) => {
    // value为选中节点数据
    pkDept.value = value.id
    // const id = pkDept.value

    getPostList()
  }
  const handleCascaderChange1 = (item: any) => {
    form.groupId = item[item.length-1]
    // console.log(queryForm.studyGroupId)
    groupIds.value = item
    // console.log(item,'item')
    if (cascaderAddr1.value) {
      // console.log('yiji-----',cascaderAddr.value,cascaderAddr.value.getCheckedNodes())
      // 获取选中节点的 pathLabels
      groupNames.value = cascaderAddr1.value.getCheckedNodes()[0].pathLabels
    }
    form.groupIds = groupIds.value
    form.groupNames = groupNames.value
    // console.log('Path Labels:', form.groupIds,form.groupNames);
    form.postIds = []
    getPostList()
    if (route.query.flag == 1){
      isShow.value = false
      flag.value = 0
      form.examPaperName = ''
    }
  };
  //学习岗位
  const getPostList =  () =>{
    const num = form.groupId
    // console.log('----',num,pkDept.value)
    syspost(num).then((res: any) => {
      Object.assign(postList, res.data)
      // console.log('----',res.data)
    });
  }
  // 返回学习标识
  const enhshsh = () =>{
    formquerlist.taskId = route.query.taskId
    const isRelateExamInt = computed(() => {
      return parseInt(formquer.isRelateExam, 10);
    });
    formquerlist.isRelateExam = isRelateExamInt.value
    formquerlist.examName = form.examName
    console.log('传值',formquerlist.isRelateExam);
    identification(formquerlist).then(res => {

    }).catch(error => {
      console.error(error);
    });
  }
  const onSubmit = () => {
    scoreList.forEach(item => {
      let obj = {
        leftBoundary: item.leftBoundary,
        rightBoundary: item.rightBoundary,
        scoreLevel: item.scoreLevel,
      }
      form.levelEntityList1.push(obj)
    })
    dataFormRef.value?.validate((valid: any) => {
      if (valid) {
        loading.value = true
        if (form.examId == undefined) {
          examinationList(form).then((res => {
            ElMessage({
              message: '创建成功',
              type: 'success',
            })
            const dataToPass = res.data;
            formquerlist.examId = res.data
            console.log(formquerlist.examId, res.data, '接入口');
            const examName = form.examName
            const examId = formquerlist.examId
            const queryParams = { data: JSON.stringify(dataToPass) }; // 将数据转换为 JSON 字符串
            console.log(queryParams,'queryParams');
            const groupIds = form.groupIds
            console.log(form.groupIds, 'form.groupIds');
            const groupNames = form.groupNames
            const postIds = form.postIds
            const postNames = form.postNames
            const encodedPersons = JSON.stringify(form.persons1);
            const encodedPersonName = form.personName
            const taskName1 = formquer.taskName
            const zymcName1 = formquer.zymcName
            console.log(zymcName1, '回显船只');
            const keyPoint1 = formquer.keyPoint
            const startTime1 = formquer.startTime
            const endTime1 = formquer.endTime
            const abnormalDays1 = formquer.abnormalDays
            const state = formquer.state
            // console.log('返回时',state);
            const examPaperId = form.examPaperId
            const isTimeLimit = formquer.isTimeLimit
            const isRelateExam = formquer.isRelateExam
            const isTopicEnd = formquer.isTopicEnd
            const isExcutePlan = formquer.isExcutePlan
            const isExamAfterData = formquer.isExamAfterData
            const dataString = route.query.encodedData;
            const taskId = route.query.taskId
            console.log(isTimeLimit, '创建');
            enhshsh()
            router.push({
              path: '/train/xxrwTaskList/study',
              query: {
                queryParams: dataToPass,
                examName1: examName,
                groupIds1: groupIds,
                groupNames1: groupNames,
                postIds1: postIds,
                postNames1: postNames,
                persons: encodedPersons,
                names: encodedPersonName,
                taskName2: taskName1,
                zymcName2: zymcName1,
                keyPoint2: keyPoint1,
                startTime2: startTime1,
                endTime2: endTime1,
                abnormalDays2: abnormalDays1,
                state: state,
                examPaperId: examPaperId,
                isTimeLimit1: isTimeLimit,
                isRelateExam1: isRelateExam,
                isTopicEnd1: isTopicEnd,
                taskId: taskId,
                isExcutePlan1: isExcutePlan,
                isExamAfterData1: isExamAfterData,
                dataString1: dataString,
                examId:examId
              }
            });
          })).catch(error => {
            alert('失败');
          })
        } else {
          delete form.xxrwTranscriptEntityList;
          sededitList(form).then((res => {
            ElMessage({
              message: '修改成功',
              type: 'success',
            })
            const state = formquer.state
            const taskId = route.query.taskId
            formquerlist.examId = res.data
            console.log(taskId, '返回学习任务id');
            const examName = form.examName
            const examId = formquerlist.examId
            console.log('编辑返回时', taskId);

            router.push({ path: '/train/xxrwTaskList/study', query: { state: state, taskId: taskId,examName:examName, examId:examId} })
            console.log(state, '编辑返回1');
          })).catch(error => {
            alert('失败');
          })
        }
      }
      enhshsh()
    })
  }
  //返回上一页
  const goBack = () => {
    // const dataToPass = res.data;
    const examName = form.examName
    // const queryParams = { data: JSON.stringify(dataToPass) }; // 将数据转换为 JSON 字符串
    const groupIds = form.groupIds
    console.log(form.groupIds,'form.groupIds');
    const groupNames = form.groupNames
    const postIds = form.postIds
    const postNames = form.postNames
    const encodedPersons = JSON.stringify(form.persons1);
    const encodedPersonName = form.personName
    const taskName1 = formquer.taskName
    const zymcName1 = formquer.zymcName
    console.log(zymcName1,'回显船只');
    const keyPoint1 = formquer.keyPoint
    const startTime1 = formquer.startTime
    const endTime1 = formquer.endTime
    const abnormalDays1 = formquer.abnormalDays
    const state = formquer.state
    const taskId = route.query.taskId
    const isTimeLimit = formquer.isTimeLimit
    const isRelateExam = formquer.isRelateExam
    const isTopicEnd = formquer.isTopicEnd
    const isExcutePlan = formquer.isExcutePlan
    const isExamAfterData = formquer.isExamAfterData
    const dataString = route.query.encodedData;
    console.log(dataString,'取消');
    router.push({ path: '/train/xxrwTaskList/study', query: { examName1: examName,groupIds1:groupIds,
        groupNames1:groupNames,postIds1:postIds,postNames1:postNames,
        persons: encodedPersons, names: encodedPersonName,
        taskName2:taskName1,zymcName2:zymcName1,keyPoint2:keyPoint1,
        startTime2:startTime1,endTime2:endTime1,abnormalDays2:abnormalDays1,
        state:state,taskId:taskId,isTimeLimit1:isTimeLimit,isRelateExam1:isRelateExam,
        isTopicEnd1:isTopicEnd,isExcutePlan1:isExcutePlan,isExamAfterData1:isExamAfterData,
        dataString1:dataString }});
    console.log(taskId,'taskId值');
  };
</script>
<style lang="scss"scoped>
  .input1{
    width: 40px;
    margin-right: 5px
  }
  .input2{
    width: 40px;
    margin-left: 5px
  }
  .input3{
    height: 32px;
    line-height: 32px;
  }
  .input4{
    border: none; /* 移除 input 的边框，如果需要的话 */
    text-align: center; /* 这将确保文本在 input 中居中 */
    width: 70px;
    margin-right: 10px
  }
  .input5{
    width: 110px;
  }
  .line{
    border-top: 1px dashed #817B7B;
    width: 1350px;
    height: 0;
    margin-left: 40px
  }
  .content{
    line-height: 50px;
    margin-left: 10px;
    font-size: 16px
  }
  .content1{
    margin-left: 14px;
    font-weight: bold
  }
</style>
